package com.xuetang9.fujian.threaddemo.pasdemo;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * @author: fujian
 * @description:
 * @date: 2021/5/3 10:50
 * @version: V1.0
 * @package: com.xuetang9.fujian.threaddemo.pasdemo
 **/
public class CharacterMachine {
    // 字符生成器的最大缓存
    private static final int MAX_BUFFER_SIZE = 20;

    private Queue<Character> charQueue = new ArrayDeque<>();

    /*
     * @Description: 随机生成字母
     * @param:
     * @return
     * @author: fujian
     * @date 2021/5/3 10:56
    */
    public synchronized void produceChar() throws InterruptedException {
        while (charQueue.size() == MAX_BUFFER_SIZE){
            wait();
        }
        int count = 0;
        while (charQueue.size() < MAX_BUFFER_SIZE){
            int randChar = ((int)(Math.random() * 10000) ) % ('Z' - 'A' + 1) + 'A';
            charQueue.offer((char)randChar);
            count++;
        }
        System.out.println("入库了" + count + "个字母");
        notify();
    }
    /*
     * @Description: 消费者消费字母
     * @param:
     * @return java.lang.Character
     * @author: fujian
     * @date 2021/5/3 10:59
    */
    public synchronized Character consumeChar() throws InterruptedException {
        // 注意点：需要不停的去判断队列中的元素
        while (charQueue.size() == 0){
            System.out.println("仓库为空等待补货。。。。");
            wait();
        }
        Character ch = charQueue.poll();
        System.out.println("消费者消费了字母：" + ch);
        return ch;
    }

}
